﻿using Minecraft.Config;
using Minecraft.Config.Csv.CsvCls;
using Minecraft.Config.Csv.CsvCom;
using Minecraft.Model;
using Minecraft.Model.Furniture;
using Minecraft.Model.ReqResp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Minecraft.ServerHall
{
	public static class FurnitureOutputUpgradeExt
	{
		/// <summary>
		/// 获取产出家具升级信息
		/// </summary>
		/// <param name="furniture"></param>
		/// <param name="session"></param>
		/// <param name="furnitureOutputUpgradeInfo"></param>
		/// <returns></returns>
		public static FurnitureOutputUpgradeInfo GetFurnitureOutputUpgradeInfo(this FurnitureModel furniture, MinecraftSession session)
		{
			var timeNow = DateTimeOffset.Now;

			//if (JsonConfig.Value.IsDebug)
			//{
			//	furniture.Upgrade_MaterialGoodsItemIdsAndNums = "100000#20|100002#20|100004#20|100009#20";
			//	furniture.Upgrade_StartTime = timeNow.AddSeconds(-1801);
			//}

			/*
			 * 逻辑：
			 * 判断升级条件：得到升级状态
			 *	达到升级条件：
			 *		判断升级持续时间：
			 *		升级持续时间小于升级总时间：
			 *			升级状态为【进行中】
			 *		升级持续时间大于等于升级总时间：
			 *			升级状态为【未开始】
			 *	未达到升级条件：
			 *		升级状态为【未开始】
			 */
			bool isCanAchieveUpgrade = false;
			FurnitureOutputUpgradeInfo furnitureOutputUpgradeInfo = null;
			Mod_Drawing csvFurnitureInfo = furniture.GetMod_FurnitureInfo();
			if (furniture.Level >= csvFurnitureInfo.MaxLevel_Convert)
			{
				return furnitureOutputUpgradeInfo;
			}
			int totalSeconds = 0;
			int remainSeconds = 0;
			EnumFurnitureOutputUpgradeState enumFurnitureOutputUpgradeState = EnumFurnitureOutputUpgradeState.NotStart;
			if (!furniture.Upgrade_State_Convert)
			{
				isCanAchieveUpgrade = furniture.GetFurnitureOutputUpgradeState(session);
				enumFurnitureOutputUpgradeState = EnumFurnitureOutputUpgradeState.NotStart;
			}
			else
			{
				if (furniture.Level > csvFurnitureInfo.MaxLevel_Convert - 1)
				{
					enumFurnitureOutputUpgradeState = EnumFurnitureOutputUpgradeState.NotStart;
					furniture.Upgrade_State = 0;
				}
				else
				{
					var upgradeModRecipeTimeInfo = csvFurnitureInfo.GetUpgradeModRecipeTimeInfoList_Convert(furniture.Level);
					totalSeconds = upgradeModRecipeTimeInfo.Second;
					isCanAchieveUpgrade = furniture.GetFurnitureOutputUpgradeState(session);
					if (isCanAchieveUpgrade)
					{
						var sustainedSeconds = Convert.ToInt32((timeNow - furniture.Upgrade_StartTime).TotalSeconds);
						if (sustainedSeconds < upgradeModRecipeTimeInfo.Second)
						{
							enumFurnitureOutputUpgradeState = EnumFurnitureOutputUpgradeState.Progressing;
							remainSeconds = upgradeModRecipeTimeInfo.Second - sustainedSeconds;
						}
						else
						{
							enumFurnitureOutputUpgradeState = EnumFurnitureOutputUpgradeState.NotStart;
							furniture.Upgrade_State = 0;
							//已经升级完成，初始化数据
							var listCopy = furniture.GetFurnitureOutputUpgradeMaterialGoodsInfoList_Convert().DeepCopy();
							for (int i = 0; i < listCopy.Count(); i++)
							{
								var item = listCopy[i];
								item.Num = 0;
								furniture.TransformListToOutput_UpgradeMaterialGoodsItemIdsPosAndNums_Convert(item);
							}
							//等级加1
							furniture.Level++;
						}
					}
					else
					{
						enumFurnitureOutputUpgradeState = EnumFurnitureOutputUpgradeState.NotStart;
						furniture.Upgrade_State = 0;
					}
				}
			}

			furnitureOutputUpgradeInfo = new FurnitureOutputUpgradeInfo
			{
				enumFurnitureOutputUpgradeState = enumFurnitureOutputUpgradeState,
				furnitureOutputUpgradeMaterialInfoList = furniture.GetFurnitureOutputUpgradeMaterialGoodsInfoList_Convert(),
				totalSeconds = totalSeconds,
				remainSeconds = remainSeconds,
				isCanAchieveUpgrade = isCanAchieveUpgrade,
			};
			if (JsonConfig.Value.IsTest)
			{
				//测试，记录结果日志
				string result = $"临时记录：时间：{timeNow.ToStr()}，家具升级结果：{furnitureOutputUpgradeInfo.JsonSerialize()}";
				session.AppServer.Logger.Debug(result);
			}
			return furnitureOutputUpgradeInfo;
		}
		/// <summary>
		/// 针对 Upgrade_MaterialGoodsItemIdsAndNums 字段转换成产出家具升级已经有的材料物品信息列表
		/// </summary>
		/// <param name="furniture"></param>
		/// <returns></returns>
		public static List<FurnitureOutputUpgradeMaterialInfo> GetFurnitureOutputUpgradeMaterialGoodsInfoList_Convert(this FurnitureModel furniture)
		{
			Mod_Drawing csvFurnitureInfo = furniture.GetMod_FurnitureInfo();

			//加上汇总排序机制，目前先按照itemid排序

			List<FurnitureOutputUpgradeMaterialInfo> furnitureOutputUpgradeMaterialInfoList = new List<FurnitureOutputUpgradeMaterialInfo>();
			var itemidsAndNumsStrs = furniture.Upgrade_MaterialGoodsItemIdsAndNums.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
			foreach (var itemidsAndNumsStr in itemidsAndNumsStrs)
			{
				var idsAndNums = itemidsAndNumsStr.Split(new char[] { '#' }, StringSplitOptions.RemoveEmptyEntries);
				FurnitureOutputUpgradeMaterialInfo furnitureOutputMaterialGoodsInfo = new FurnitureOutputUpgradeMaterialInfo
				{
					GoodsItemId = idsAndNums[0],
					Num = int.Parse(idsAndNums[1])
				};
				furnitureOutputUpgradeMaterialInfoList.Add(furnitureOutputMaterialGoodsInfo);
			}

			if (furniture.Level >= csvFurnitureInfo.MaxLevel_Convert)
			{
				return new List<FurnitureOutputUpgradeMaterialInfo>();
			}

			var UpgradeCompositing = csvFurnitureInfo.GetUpgradeCompositingList_Convert(furniture.Level);
			int position = -1;
			furnitureOutputUpgradeMaterialInfoList = UpgradeCompositing.modRecipeInfoList_Convert.ConvertAll(r =>
			{
				var materialInfo = furnitureOutputUpgradeMaterialInfoList.FirstOrDefault(m => m.GoodsItemId == r.GoodsItemId);
				if (materialInfo != null)
				{
					return new FurnitureOutputUpgradeMaterialInfo
					{
						GoodsItemId = materialInfo.GoodsItemId,
						needNum = r.Num,
						Num = materialInfo.Num
					};
				}
				else
				{
					return new FurnitureOutputUpgradeMaterialInfo
					{
						GoodsItemId = r.GoodsItemId,
						needNum = r.Num,
						Num = 0,
					};
				}
			})
			.OrderBy(m => m.GoodsItemId)
			.ToList().ConvertAll(r =>
			{
				position++;
				return new FurnitureOutputUpgradeMaterialInfo()
				{
					GoodsItemId = r.GoodsItemId,
					position = position,
					needNum = r.needNum,
					Num = r.Num
				};
			}).ToList();

			return furnitureOutputUpgradeMaterialInfoList;
		}
		/// <summary>
		/// 针对 Upgrade_MaterialGoodsItemIdsAndNums 字段的修改要从对象列表转换成字符串
		/// </summary>
		/// <param name="furniture"></param>
		/// <param name="furnitureOutputMaterialGoodsInfo"></param>
		public static void TransformListToOutput_UpgradeMaterialGoodsItemIdsPosAndNums_Convert(this FurnitureModel furniture,
			FurnitureOutputUpgradeMaterialInfo furnitureOutputUpgradeMaterialInfo)
		{
			var list = furniture.GetFurnitureOutputUpgradeMaterialGoodsInfoList_Convert();
			var index = list.FindIndex(m => m.GoodsItemId == furnitureOutputUpgradeMaterialInfo.GoodsItemId);
			if (index >= 0)
			{
				list.RemoveAt(index);
			}
			list.Add(furnitureOutputUpgradeMaterialInfo);
			furniture.Upgrade_MaterialGoodsItemIdsAndNums = string.Join("|", list.ToList().ConvertAll(info =>
			{
				return string.Join("#", info.GoodsItemId, info.Num);
			}).ToArray());
		}
		/// <summary>
		/// （针对产出家具，升级）是否满足产出家具升级条件
		/// </summary>
		/// <param name="furniture"></param>
		/// <param name="session"></param>
		/// <returns></returns>
		public static bool GetFurnitureOutputUpgradeState(this FurnitureModel furniture, MinecraftSession session)
		{
			//耐久度hp是否大于0，材料是否足够

			if (furniture.Hp <= 0)
			{
				return false;
			}
			//家具的配置信息
			Mod_Drawing csvFurnitureInfo = furniture.GetMod_FurnitureInfo();
			if (csvFurnitureInfo == null) //家具表中该家具配置不存在，则数据库信息存在错误，或者配置表出现错误
			{
				string errorTips = $"指定家具配置信息不存在（FurnitureItemId：【{furniture.FurnitureItemId}】）";
				session.AppServer.Logger.Fatal(errorTips);
				return false;
			}
			var isCanAchieveUpgrade = furniture.GetFurnitureOutputUpgradeMaterialGoodsInfoList_Convert().All(m => m.Num >= m.needNum);
			return isCanAchieveUpgrade;
		}

	}
}
